<?php
namespace Library;

use \Library\SecConfig;

/**
 * RSA加密解密
 * @author jetking
 */
class Rsa
{

    /**
     * 返回对应的私钥
     */
    private static function getPrivateKey()
    {
        //$privKey = self::$PRIVATE_KEY;

        $securityConfig = SecConfig::read('security');
        $privKey = $securityConfig->app_http->private_key;

        return openssl_pkey_get_private($privKey);
    }

    /**
     * 返回对应的私钥
     */
    private static function getPublicKey()
    {
        //$publicKey = self::$PUBLIC_KEY;

        $securityConfig = SecConfig::read('security');
        $publicKey = $securityConfig->app_http->public_key;

        return openssl_pkey_get_public($publicKey);
    }

    /**
     * 私钥加密
     */
    public static function privEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, self::getPrivateKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * 私钥解密
     */
    public static function privDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey())) ? $decrypted : null;
    }

    /**
     * 公钥加密
     */
    public static function publicEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data, $encrypted, self::getPublicKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * 公钥解密
     */
    public static function publicDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey())) ? $decrypted : null;
    }

    /**
     * 私钥解密,不做Base64解码
     * @param string $encrypted
     * @return NULL|Ambigous <unknown, NULL>
     */
    public static function privDecryptNB64($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt($encrypted, $decrypted, self::getPrivateKey())) ? $decrypted : null;
    }

    /**
     * 分段私钥解密
     * @param string $encrypted
     * @return Ambigous <string, NULL, Ambigous, unknown>
     */
    public static function partPrivDecrypt($encrypted)
    {
        if (substr($encrypted, 0, 5) == '#####') { //开发调试模式
            $encrypted = str_replace('#####', '', $encrypted);
            return $encrypted;
        }
        $encrypted = base64_decode($encrypted);
        $fp = fopen("php://memory", 'w+b');
        fwrite($fp, $encrypted);
        fseek($fp, 0);
        $bContent = '';
        while (!feof($fp)) {
            $bContent .= self::privDecryptNB64(fread($fp, 128));
        }
        fclose($fp);
        return $bContent;
    }

}
